package com.xyz.controller;
import com.xyz.entity.User;
import com.xyz.pojo.Result;
import com.xyz.service.UserService;
import com.xyz.util.JwtUtils;
import com.xyz.vo.UserVO;
import com.xyz.util.PasswordUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;


@RestController
public class UserController {
    @Autowired
    private UserService userService;

    @PostMapping("/register")
    public Result register(@RequestBody UserVO userVO) {//为什么要uservo
//        User user = new User();
//        user.setUsername(userVO.getUsername());
//        user.setPassword(PasswordUtil.encrypt(userVO.getPassword()));
        User user = userService.login(userVO.getUsername(), PasswordUtil.encrypt(userVO.getPassword()));
        if (user == null) {
            userService.register(userVO);
            return Result.success("注册成功");
        }

        return Result.error("已经有该用户存在!");
//如果已经有该人存在

    }

    @PostMapping("/login")
    public Result login(@RequestBody UserVO userVO) {
        User user = userService.login(userVO.getUsername(), PasswordUtil.encrypt(userVO.getPassword()));//可以直接传吗
      //先不修改这里的逻辑了，开始发布商品吧

        //判断:登录用户是否存在，发放令牌
        if (user != null) {
//自定义信息
                Map<String,Object> claims = new HashMap<>();
                claims .put("username",user.getUsername());//唯一
            claims .put("userid",user.getUserId());
            String jwtToken = JwtUtils.createJwt(claims, JwtUtils.JWT_WEB_TTL);
//使用JWT工具类，生成身份令牌
                return Result.success(jwtToken);
        }

        return Result.error("用户名或密码错误");

    }

}
